package cn.edu.zstu.qingzhu.qingzhushop.service.impl;

import cn.edu.zstu.qingzhu.qingzhushop.entity.GoodsCategory;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.GoodsCategoryMapper;
import cn.edu.zstu.qingzhu.qingzhushop.service.IGoodsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ShenTuZhiGang
 * @since 2020-11-08
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements IGoodsCategoryService {
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Override
    public List<GoodsCategory> listWithTree() {
        //1、查出所有分类
        List<GoodsCategory> entities = goodsCategoryMapper.selectList(null);

        //2、组装成父子的树形结构
        //2.1找到所有的一级分类
        List<GoodsCategory> level1Menus = entities.stream()
                .filter((goodsCategory) -> goodsCategory.getParentId() == 0)
                .peek((menu) -> menu.setChildren(getChildren(menu, entities)))
                .sorted((menu1, menu2) -> (menu1.getCategoryRank() == null ? 0 : menu1.getCategoryRank()) - (menu2.getCategoryRank() == null ? 0 : menu2.getCategoryRank()))
                .collect(Collectors.toList());

        return level1Menus;
    }

    //递归查找所有菜单的子菜单
    private List<GoodsCategory> getChildren(GoodsCategory root, List<GoodsCategory> all) {
        List<GoodsCategory> child = all.stream()
                .filter(GoodsCategory -> GoodsCategory.getParentId().equals(root.getId()))
                //找到子菜单
                .peek(GoodsCategory -> GoodsCategory.setChildren(getChildren(GoodsCategory, all)))
                //菜单的排序
                .sorted((menu1, menu2) -> (menu1.getCategoryRank()) == null ? 0 : menu1.getCategoryRank() - (menu2.getCategoryRank() == null ? 0 : menu2.getCategoryRank()))
                .collect(Collectors.toList());
        return child.isEmpty() ? null : child;
    }

}
